# _*_ coding: utf-8 _*_
"""
@ 时间    ：2024/10/24 16:19
@ 作者    ：旺财
@ 文件    ：03-2 XGBoost-信用卡评分模型.py
@ 说明    ：
"""
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, accuracy_score, roc_auc_score, roc_curve
from xgboost import XGBRegressor
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV

# 1.读取数据
df = pd.read_excel('信用评分卡模型.xlsx')
print(df.head())

# 2.提取特征变量与目标变量
x = df.drop(columns='信用评分')
y = df['信用评分']

# 3.拆分训练集与测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=123)

# 4.搭建并调优模型
param_grid = {
    'max_depth': [1, 3, 5],
    'n_estimators': [50, 100, 150],
    'learning_rate': [0.01, 0.05, 0.1, 0.2]
}
mode = XGBRegressor()
grid_search = GridSearchCV(mode, param_grid, cv=5, scoring='r2')
grid_search.fit(x_train, y_train)
best_model = grid_search.best_estimator_
best_params = grid_search.best_params_
print(best_params)

# 5.评估模型
# 预测结果
df_score = pd.DataFrame()
df_score['预测结果'] = list(best_model.predict(x_test))
df_score['实际结果'] = list(y_test)
print(df_score.head())

# 打印准确率
mse = mean_squared_error(y_test, df_score['预测结果'])
mae = mean_absolute_error(y_test, df_score['预测结果'])
score = best_model.score(x_test, y_test)
print(f'均方误差（MSE）为：{mse}')
print(f'平均绝对误差（MAE）为：{mae}')
print(f'模型精准度（R²）为：{round(score*100, 2)}%')

# 打印特征变量
df_importance = pd.DataFrame()
df_importance['特征名称'] = x.columns
df_importance['特征重要性'] = best_model.feature_importances_
print(df_importance)
